//
//  NetworkTools.swift
//  06-AFN网络封装（swift）
//
//  Created by 白利兵 on 15/10/16.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking
enum HMRequestMethod: String{
    case GET = "GET"
    case POST = "POST"
}
class NetworkTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    //App Key：3191662843 刀哥：1407267207
    // App Secret：c8d40ad85ef574d27a35337b4e26d34a 刀哥：6b66590f29bad6e7e7dd4c7b0c4dfa50
    private let appKey =  "3191662843"
    private let appSecret = "c8d40ad85ef574d27a35337b4e26d34a"
    private let redirectUrl = "http://www.baidu.com"
    // 创建单例
    static let sharedTools: NetworkTools = {
        let tools = NetworkTools(baseURL: nil)
        // 设置反序列化数据格式，系统会把OC的NSSet格式转化为set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    var tokenDict: [String: AnyObject]? {
        return UserAccountViewModel.shareUserAccount.tokenDict!
    }
}
// MARK: - Author的方法
extension NetworkTools {
    // 定义一个回调
    typealias HMRequestCallBack = (result: AnyObject?, error: NSError?)->()
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    // 获取用户微博信息
    func loadStatus(since_id: Int, max_id: Int,  finished: HMRequestCallBack) {

        // 获取token字典
        print(tokenDict)
        guard var params = tokenDict else {
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token值为空"]))
            return
        }
        if since_id > 0 {
            params["since_id"] = since_id
        }
        else if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        // 获取网络请求地址
        // 3902313355638913
        // 3902312495816048
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 加载数据
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    }
    // 获取Accesstoken
    func loadAccessToken(code: String, finished: HMRequestCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parame = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        // 发送请求
        request(HMRequestMethod.POST, URLString: urlString, parameters: parame, finished: finished)
    }
    // 获取用户信息
    func loadUserInfo(uid: String, finished: HMRequestCallBack) {
        // https://api.weibo.com/2/users/show.json
        // https://api.weibo.com/2/statuses/user_timeline.json
        let urlString = "https://api.weibo.com/2/users/show.json"
        guard var params = tokenDict else {
            finished(result: nil, error: NSError(domain: "cn.itheima.error", code: -1001, userInfo: ["message": "字典为空"]))
            return
        }
        params["uid"] = uid
        // 发送请求
        request(.GET, URLString: urlString, parameters: params, finished: finished)
        }
    // 发布一条微博
    // https://upload.api.weibo.com/2/statuses/upload.json
    func sendStatus(status: String, image: UIImage?, finished: HMRequestCallBack){
        
        guard var params = tokenDict else {
            
            finished(result: nil, error: NSError(domain: "cn.itheima.error", code: -1001, userInfo: ["message": "字典为空"]))
            return
        }
        params["status"] = status
        if image == nil {
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            // 发送请求
            request(.POST, URLString: urlString, parameters: params, finished: finished)
            return
        }
        else {
            let data = UIImagePNGRepresentation(image!)
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            // 发送请求
            upload(urlString, data: data!, name: "pic", parameters: params, finished: finished)
        }
        
    }
    // 上传图片的网络请求方法
    private func upload(urlString: String, data: NSData, name: String, parameters: [String: AnyObject], finished: HMRequestCallBack) {
        // 发送POST请求
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            // 设置formData格式
            formData.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            }, success: { (_, result) -> Void in
                // 成功的回调
                finished(result: result, error: nil)
            }) { (_, error) -> Void in
                // 失败的回调
                finished(result: nil, error: error)
        }
    }
}



// MARK: - 封装网络方法
extension NetworkTools {
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调

    func request(methodName: HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished:HMRequestCallBack) {
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
                finished(result: nil, error: error)
        }
        if methodName == HMRequestMethod.GET{
            GET(URLString, parameters: parameters, success: success, failure: failure)
        }
        else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
}














